package com.alibaba.dingtalk.openapi.newmessage.helper;

import com.alibaba.dingtalk.openapi.newmessage.entity.OA;
import com.alibaba.dingtalk.openapi.newmessage.entity.template.TemplateMessage;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.pro.config.ProBaseConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
public class TemplateMessageTransferHelper {

    @Resource
    private ProBaseConfig proBaseConfig;

    private static final String DINGTALK_SLIDE = "dingtalk://dingtalkclient/page/link?url=";

    private static final String DINGTALK_SLIDE_END = "&pc_slide=true";

    private static final String DINGTALK_WORKSTATION = "dingtalk://dingtalkclient/action/openapp?corpid=";

    private static final String DINGTALK_WORKSTATION_START = "&redirect_type=jump&redirect_url=";

    public TemplateMessage transferToTemplateMessage(OA oaMessage) {
        Integer size = 0;
        JSONObject formObj = null;
        if (!Objects.isNull(oaMessage.getBody().getForm())) {
            size = oaMessage.getBody().getForm().size();
            formObj = new JSONObject();
            for (OA.Body.Form form : oaMessage.getBody().getForm()) {
                formObj.put(form.getKey(), form.getValue());
            }
        }

        Map<String, String> templates = proBaseConfig.getTemplates();
        String templateId = templates.get(size.toString());



        String pcMessageUrl = oaMessage.getPcMessageUrl();
//        if (pcMessageUrl.startsWith(DINGTALK_SLIDE)) {
//            int start = pcMessageUrl.indexOf(DINGTALK_SLIDE);
//            int end = pcMessageUrl.lastIndexOf(DINGTALK_SLIDE_END);
//            String substring = pcMessageUrl.substring(start, end);
//            pcMessageUrl = URLEncodeUtils.decodeURL(substring);
//        } else if (pcMessageUrl.startsWith(DINGTALK_WORKSTATION)) {
//            int start = pcMessageUrl.indexOf(DINGTALK_WORKSTATION_START);
//            String substring = pcMessageUrl.substring(start);
//            pcMessageUrl = URLEncodeUtils.decodeURL(substring);
//        }

        TemplateMessage.FormMessage formMessage = new TemplateMessage.FormMessage(oaMessage.getHead().getText(), oaMessage.getBody().getTitle(), oaMessage.getBody().getContent(), formObj, oaMessage.getMessageUrl(), pcMessageUrl);

        // 如果没有对应form数量的模板，就取标准的没有form的模板。做个保险
        if (Objects.isNull(templateId)) {
            templateId = templates.get("0");
        }

        return new TemplateMessage(templateId, formMessage);
    }
}
